package current.voltails;

import java.util.concurrent.TimeUnit;

/**
 * volatile阻止CPU指令重排，确保语义上对变量的读写操作能被观察到
 */
public class ReOrder {
    // static int a = 0;
    volatile static int a = 0;

    public static void main(String[] args) {
        Runnable r1 = () -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 不能保证a在线程之间传递, 解决方法：使用volatile关键字
            a = 1000;
            System.out.println("set a");
        };

        Runnable r2 = () -> {
          // 能感应到之前a的变化
          while (a < 100) {

          }
          System.out.println("end: " + a);
        };

        new Thread(r1).start();
        new Thread(r2).start();
    }
}
